package com.toidep.adapters;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebSettings.TextSize;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.toidep.R;
import com.toidep.activities.MainActivity;
import com.toidep.api.ApiController;
import com.toidep.api.ParseJSON;
import com.toidep.base.BaseFragment;
import com.toidep.config.ConfigUtility;
import com.toidep.entities.ArticleEntity;
import com.toidep.fragment.others.NewsDetailFragment;
import com.toidep.info.NewsDetailHolder;
import com.toidep.interfaces.ResponseListener;
import com.toidep.widgets.viewflow.newsdetail.TitleProvider;

@SuppressLint("NewApi")
public class AsyncAdapter extends BaseAdapter implements TitleProvider {

	private LayoutInflater mInflater;
	private BaseFragment parentFragment;
	public ArrayList<ArticleEntity> listNews;
	public ArrayList<ViewHolder> arrViewHolder;
	public ArrayList<LoadContentTask> arrTask;
	private int newType;
	
	private int zoomLv;
	private TextSize textSizeWeb;
	
	private MainActivity mainActivity;

	public AsyncAdapter(BaseFragment bf, ArrayList<ArticleEntity> list, int type) {
		this.parentFragment = bf;
		mainActivity = (MainActivity)parentFragment.getActivity();
		mInflater = (LayoutInflater) mainActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		this.newType = type;
		arrViewHolder = new ArrayList<AsyncAdapter.ViewHolder>();
		listNews = new ArrayList<ArticleEntity>();
		listNews.addAll(list);
		arrTask = new ArrayList<AsyncAdapter.LoadContentTask>();

		int size = listNews.size();
		for (int i = 0; i < size; i++) {
			arrTask.add(new LoadContentTask(i, listNews.get(i)));
			arrViewHolder.add(null);
		}
		
		zoomLv = 0;
	}

	public void zoomIn() {
		if (zoomLv < 2) {
			zoomLv++;
			for (ViewHolder viewHolder : arrViewHolder) {
				viewHolder.zoomIn();
			}
		}

	}

	public void zoomOut() {
		if (zoomLv > -2) {
			zoomLv--;
			for (ViewHolder viewHolder : arrViewHolder) {
				viewHolder.zoomOut();
			}
		}

	}

	public ArticleEntity getItem(int position) {
		return listNews.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public class ViewHolder {
		public TextView textNewsTittle, textNewsTime;
		public WebView webView;
		public LinearLayout webContain;
		public ImageView imageViewAvatar;
		// public ScrollView scrollView;
		public LinearLayout layoutLoading, layoutError;
		public View view;

		public TextSize textSizeWeb;

		// For share
		public String newTitle = "";
		public String newThumbnailUrl = "";
		public String newUrlDetail = "";
		public String newDescription = "";

		public void clear() {
			if (webView != null) {
				webView.freeMemory();
				webView.destroy();
				webView = null;
			}
		}

		public void zoomIn() {
			if (webView != null) {

				WebSettings webSettings = webView.getSettings();
				textSizeWeb = webSettings.getTextSize();

				if (textSizeWeb != WebSettings.TextSize.LARGEST) {
					if (textSizeWeb == WebSettings.TextSize.SMALLEST) {
						textSizeWeb = WebSettings.TextSize.SMALLER;
					} else if (textSizeWeb == WebSettings.TextSize.SMALLER) {
						textSizeWeb = WebSettings.TextSize.NORMAL;
					} else if (textSizeWeb == WebSettings.TextSize.NORMAL) {
						textSizeWeb = WebSettings.TextSize.LARGER;
					} else if (textSizeWeb == WebSettings.TextSize.LARGER) {
						textSizeWeb = WebSettings.TextSize.LARGEST;
					}
					webSettings.setTextSize(textSizeWeb);
				}
			}
		}

		public void zoomOut() {

			if (webView != null) {
				WebSettings webSettings = webView.getSettings();
				textSizeWeb = webSettings.getTextSize();

				if (textSizeWeb != WebSettings.TextSize.SMALLEST) {
					if (textSizeWeb == WebSettings.TextSize.LARGEST) {
						textSizeWeb = WebSettings.TextSize.LARGER;
					} else if (textSizeWeb == WebSettings.TextSize.LARGER) {
						textSizeWeb = WebSettings.TextSize.NORMAL;
					} else if (textSizeWeb == WebSettings.TextSize.NORMAL) {
						textSizeWeb = WebSettings.TextSize.SMALLER;
					} else if (textSizeWeb == WebSettings.TextSize.SMALLER) {
						textSizeWeb = WebSettings.TextSize.SMALLEST;
					}
					webSettings.setTextSize(textSizeWeb);
				}
			}
		}
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		return drawView(position, convertView);
	}

	private View drawView(int position, View view) {
		final ViewHolder viewHolder;
		if (view == null) {
			view = mInflater.inflate(R.layout.item_news_detail, null);
			viewHolder = new ViewHolder();
			viewHolder.textNewsTittle = (TextView) view.findViewById(R.id.tittleNews);
//			viewHolder.textNewsTime = (TextView) view.findViewById(R.id.publishTime);
			viewHolder.webContain = (LinearLayout) view.findViewById(R.id.webcontain);
			viewHolder.imageViewAvatar = (ImageView) view.findViewById(R.id.thumbnail);
			// viewHolder.scrollView = (ScrollView)
			// view.findViewById(R.id.scrollView);
			viewHolder.layoutLoading = (LinearLayout) view.findViewById(R.id.layoutLoading);
			viewHolder.layoutLoading.setVisibility(View.GONE);
			viewHolder.layoutError = (LinearLayout) view.findViewById(R.id.layoutError);
			viewHolder.layoutError.setVisibility(View.GONE);
			viewHolder.view = view;
			view.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) view.getTag();

		}

		try {
			ArticleEntity newInfo = listNews.get(position);
			if (newInfo != null) {
				arrViewHolder.set(position, viewHolder);
				if (position == NewsDetailHolder.getCurrentPosition()) {
					LoadContentTask loadContentTask = arrTask.get(position);
					loadContentTask.setView(arrViewHolder.get(position).view);
					loadContentTask.setViewHolder(arrViewHolder.get(position));
					loadContentTask.loadContent();
				}
			} else {
			}
		} catch (Exception e) {
		}

		return view;
	}

	public void loadViewByPosition(int pos) {

		ArticleEntity newInfo = listNews.get(pos);
		if (newInfo != null) {
			if (pos == NewsDetailHolder.getCurrentPosition()) {
				LoadContentTask loadContentTask = arrTask.get(pos);
				loadContentTask.setView(arrViewHolder.get(pos).view);
				loadContentTask.setViewHolder(arrViewHolder.get(pos));
				loadContentTask.loadContent();
			}
		}
	}

	public class LoadContentTask {
		// private int position;
		private View view;
		public ArticleEntity newsInfo;
		public ViewHolder viewHolder;

		public LoadContentTask(int p, ArticleEntity newsInfo) {
			this.newsInfo = newsInfo;
		}

		public View getView() {
			return view;
		}

		public void setView(View view) {
			this.view = view;
		}

		public ViewHolder getViewHolder() {
			return viewHolder;
		}

		public void setViewHolder(ViewHolder viewHolder) {
			if (this.viewHolder == null)
				this.viewHolder = viewHolder;
		}
		
		public void setZoomLVForWebview(WebSettings webSettings, int zoomLV) {
			switch (zoomLV) {
			case -2:
				textSizeWeb = WebSettings.TextSize.SMALLEST;
				webSettings.setTextSize(textSizeWeb);
				
				break;
			case -1:
				textSizeWeb = WebSettings.TextSize.SMALLER;
				webSettings.setTextSize(textSizeWeb);
				
				break;
			case 0:
				textSizeWeb = WebSettings.TextSize.NORMAL;
				webSettings.setTextSize(textSizeWeb);
				break;
			case 1:
				textSizeWeb = WebSettings.TextSize.LARGER;
				webSettings.setTextSize(textSizeWeb);
				break;
			case 2:
				textSizeWeb = WebSettings.TextSize.LARGEST;
				webSettings.setTextSize(textSizeWeb);
				break;
			}
		}

		public void loadContent() {
			viewHolder.layoutLoading.setVisibility(View.VISIBLE);
			viewHolder.layoutError.setVisibility(View.GONE);
			
			if (((NewsDetailFragment) parentFragment).cacheNewsDetail == null || ((NewsDetailFragment) parentFragment).cacheNewsDetail.containsKey(newsInfo.getId()) == false) {
		
				ApiController.getNewDetail(
						mainActivity,
						"" + newsInfo.getId(),
						new ResponseListener() {
	
					public void processResponse(String response) {
						// Log.e("AsyncAdapter", response);
						if (response != null) {
							try {
								newsInfo = ParseJSON.getNewsDetailFromResponse(response);
								if (newsInfo != null) {
									// NewsDetailHolder.listNewInfo.get(NewsDetailHolder.getCurrentPosition()).setUrlDetail(newsInfo.getThumbnailUrl());

									((NewsDetailFragment) parentFragment).cacheNewsDetail.put("" + newsInfo.getId(), newsInfo);
									if (newsInfo != null) {
										//295 - start
										String imageTag = "<img src = "+ newsInfo.getImageUrl() +"> ";
										String newDescription = imageTag+"<br/><br/>"+newsInfo.getContent();		// HTML
										//295 - stop
										viewHolder.textNewsTittle.setText(newsInfo.getTitle());
//										viewHolder.textNewsTime.setText(newsInfo.getTime());

										viewHolder.webView = new WebView(mainActivity.getApplicationContext());
										viewHolder.webContain.addView(viewHolder.webView);
										getContent(newDescription, newsInfo.getTitle(), newsInfo.getCreated());
										viewHolder.layoutLoading.setVisibility(View.GONE);
										// viewHolder.scrollView.scrollTo(0, 0);
									}
								}
							} catch (Exception e) {
								viewHolder.layoutLoading.setVisibility(View.GONE);
								viewHolder.layoutError.setVisibility(View.VISIBLE);
							}
						}
					}

					@Override
					public void processResponse(int inintstall) {
						viewHolder.layoutLoading.setVisibility(View.GONE);
						viewHolder.layoutError.setVisibility(View.VISIBLE);
					}
				});
			} else {
				newsInfo = ((NewsDetailFragment) parentFragment).cacheNewsDetail.get(newsInfo.getId());
				if (newsInfo != null) {
					String newDescription = newsInfo.getContent(); // HTML
//					viewHolder.textNewsTittle.setText(newsInfo.getTitle());
//					viewHolder.textNewsTime.setText(newsInfo.getTime());
					// Log.e("XU LY TIN", newsDetail.getTittleNews());
					viewHolder.webView = new WebView(mainActivity.getApplicationContext());
					viewHolder.webContain.addView(viewHolder.webView);
					getContent(newDescription, newsInfo.getTitle(), newsInfo.getCreated());
					viewHolder.layoutLoading.setVisibility(View.GONE);
					viewHolder.layoutError.setVisibility(View.GONE);
//					viewHolder.scrollView.scrollTo(0, 0);
				}
			}
		}

		public void getContent(String s, String tittle, String time) {

			AsyncTask<String, String, String> asyn = new AsyncTask<String, String, String>() {

				@Override
				protected String doInBackground(String... params) {
					String temp = "<html><head><style>img{max-width:100%;height:auto !important;width:auto !important;}; span{color:#000000;font-size:12px;}</style>" 
							
							+ "</head><body style='margin:5; padding:2;text-align:justify;color:black;overflow-y: scroll;overflow-x: hidden;'>"
							+ "<h4 style='color:#000000;text-align:center'>" +params[1] + "</h4>"
							+ "<p style='color:#868686;text-align:center '>" +params[2] + "</p>"
							+ params[0] + "" 
							+"</body>"
							+"</html>";
					temp = temp.replaceAll("[<](/)?object[^>]*[>]", "");
					temp = temp.replaceAll("[<](/)?iframe[^>]*[>]", "");
					temp = temp.replaceAll("<table", "<p");
					temp = temp.replaceAll("</table>", "</p>");
					temp = temp.replaceAll("<TABLE", "<p");
					temp = temp.replaceAll("</TABLE>", "</p>");
//					temp = temp.replace("src=\"{/}", "src=\"http://farm04.gox.vn/edu/EOlympic/ImageNews/");
					temp = temp.replace("#000000", "#FFFFFF");
					temp = temp.replace("</strong>", "</strong>&nbsp;");
					temp = temp.replace("font-size: small;", "");
					Pattern tags = Pattern.compile("</?[a]{1}[^>]+>");
					Matcher match = tags.matcher(temp);
					temp = match.replaceAll("");
					temp = temp.replace("</a>", "");

					if (temp.indexOf("data:image/png;base64") >= 0 || temp.indexOf("data:image/jpeg;base64") >= 0) {
						temp = temp.replaceAll("\\<img.*?>", "");
					}

					Log.e("AsyncAdapter - formatted", temp);

					final String ss = temp;
					// Log.e("XU LY HTML", "true");
					loadHTML(temp);

					return temp;
				}

				@Override
				protected void onPostExecute(String result) {
					// Load web content

				}
			};
			asyn.execute(s,tittle, time);
		}

		public void loadHTML(String htmlContent) {
			try {
				final String html = htmlContent;
				final String mime = "text/html";
				final String encoding = "utf-8";
				
				WebSettings webSettings = viewHolder.webView.getSettings();
				webSettings.setJavaScriptEnabled(false);
				setZoomLVForWebview(webSettings, zoomLv);
				viewHolder.webView.setBackgroundColor(Color.TRANSPARENT);
				if (ConfigUtility.os_version >= 11) {
					viewHolder.webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
				}
				viewHolder.webView.setBackgroundColor(Color.TRANSPARENT);

				mainActivity.runOnUiThread(new Runnable() {

					public void run() {
						viewHolder.webView.loadDataWithBaseURL(null, html, mime, encoding, null);
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public String getTitle(int position) {
		return null;
	}

	public int getCount() {
		return listNews.size();
	}

	public void clear() {

		listNews.clear();
		arrViewHolder.clear();
		arrTask.clear();
		notifyDataSetChanged();
	}

	public void clearWebView() {
		for (ViewHolder viewHolder : arrViewHolder) {
			if (viewHolder.webView != null) {
				viewHolder.webView.freeMemory();
				viewHolder.webView.destroy();
				viewHolder.webView = null;
			}
		}
	}

	public void clearWebViewAtPosition(int pos) {
		try {
			ViewHolder view = arrViewHolder.get(pos);
			arrViewHolder.get(pos).webContain.removeAllViews();
			view.webView.freeMemory();
			view.webView.destroy();
			view.webView = null;
		} catch (Exception e) {
		}
	}

	public void clearWebViewWithoutPosition(int pos) {
		int p = 0;
		for (ViewHolder viewHolder : arrViewHolder) {
			if (viewHolder.webView != null && p != pos) {
				viewHolder.webView.freeMemory();
				viewHolder.webView.destroy();
				viewHolder.webView = null;
			}
			p++;
		}
	}
	
}
